package tjs.study.notes.dotest.jvm.classload;

import com.sun.org.apache.regexp.internal.RE;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class OtherPackagerClassLoader extends ClassLoader {

    private String loaderPath;

    public OtherPackagerClassLoader(String path) {
        loaderPath = path;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException {
        if ("tjs.study.notes.dotest.jvm.classload.agent.IPlugin".equals(name)) {
            return super.loadClass(name, resolve);
        }
        Class<?> loadedClass = this.findLoadedClass(name);
        if (loadedClass == null) {
            try {
                // 打破双亲委派机制，优先自己加载
                loadedClass = this.findClass(name);
            } catch (ClassNotFoundException var9) {
                //java.lang等包不能由自定义的类加载器加载
                loadedClass = Class.forName(name, false, this.getParent());
            }
        }

        if (resolve) {
            this.resolveClass(loadedClass);//todo 不知道这个干嘛用的,注释也能正常运行。native方法调用了JVM_ResolveClass，其是做什么的
        }

        return loadedClass;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        File file = new File(loaderPath + "/" + name.replaceAll("\\.", "/") + ".class");
        if (!file.exists()) {
            throw new ClassNotFoundException(name);//非当前工作目录的类，由父加载器加载
        }
        int len = 0;
        byte[] data = null;
        try (FileInputStream is = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
            while ((len = is.read()) != -1) {
                bos.write(len);
            }
            data = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return defineClass(name, data, 0, data.length);//装载到jvm中
    }
}
